import { BASE_URL } from '../../apis/requests.js';
const getDateDiff = require('../../utils/time.js').getDateDiff
const formatTime = require('../../utils/time.js').formatTime
const getNewDate = require('../../utils/time.js').getNewDate
// pages/borrowState/borrowState.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    books:[],
    remain_days: [],
    notes: []
  },

  bindRenew(e) {
    //console.log(e.currentTarget.dataset.index)

    const values = {
      "token": wx.getStorageSync('token'),
      "book_id": this.data.books[e.currentTarget.dataset.index].book_id
    }

    wx.request({
      url: BASE_URL + "/user/delay",
      data: values,
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      dataType: 'json',
      success: (result) => {
        console.log(result)
        if (result.data.code === "200") {
          wx.showModal({
            title: "提示",
            content: "续借成功！",
            showCancel: false,
            success(res) {
              wx.navigateBack({
                complete: (res) => {},
              })
            }
          })
        }
          
      },
      fail: () => {},
      complete: () => {}
    })

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this
    const values = {
      "token": wx.getStorageSync('token')
    }
    // 获取借书历史
    wx.request({
      url: BASE_URL + "/user/find_borrow_state",
      data: values,
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      dataType: 'json',
      success: (result) => {
        console.log(result)
        if (result.data.code === "200") {
          this.setData({
            books: result.data.data
          })
        }

        // TODO: 剩余时间显示
        for(let index in that.data.books) {
          let time = that.data.books[index].should_return_date.slice(0, 10)
          let dateDiff = getDateDiff(formatTime(new Date()), time)
          let note = null
          if (parseInt(dateDiff) >= 0) {
            note = "剩余" + dateDiff + "天"
          } else {
            note = "超期" + -dateDiff + "天"
          }
          console.log(note)

          that.setData({
            remain_days: this.data.remain_days.concat(dateDiff),
            notes: this.data.notes.concat(note)
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {    
    let remainDate = getDateDiff()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})